<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
use think\request;
use think\Session;

class Register extends Base{

//    public function index(Request $request){
//        $get=$request->get();
//        $refereecode=isset($get['refereecode'])?$get['refereecode']:'';
//        $idcard=Db::name('agents')->where('id',$refereecode)->value('idcard');
//        if($idcard==1){
//            return view('Register/indexs');
//        }else{
//            return view('Register/index');
//        }
//    }

    public function index(){
        return view('Register/indexs');
    }

	//注册添加
	public function userAdd(Request $request){
//        dump($_POST);
	    $param = myarr($request->post());
		$mobile = $param['mobile'];
		$pwd = $param['pwd'];
		$pwds = $param['pwds'];
		$code = $param['code'];
		// $refereecode = isset($_POST['refereecode'])?$_POST['refereecode']:'';
		// if(Db::name('user_code')->where('mobile',$mobile)->order('id','desc')->find() == 1) return json_encode(['msg'=>'验证码已经被使用请重新获取'])
		if(preg_match('/(^1[3|4|5|6|7|8|9]\d{9}$)|(^09\d{8}$)/', $mobile)!= 1){
			$this->error('手机号格式错误','Userregister/index',1);
		}
		if(preg_match('/^[A-Za-z0-9]{6,16}|\d{6,16}|[A-Za-z]{6,16}$/',$pwd) != 1){
			$this->error('密码格式错误','Userregister/index',1);
		}
		if(preg_match('/^[A-Za-z0-9]{6,16}|\d{6,16}|[A-Za-z]{6,16}$/',$pwds)!= 1){
			$this->error('密码格式错误','Userregister/index',1);
		}		
		if(preg_match('/^\d{4,}$/', $code)!= 1){
			$this->error('验证码格式错误','Userregister/index',1);
		}
		if(empty($_POST['refereecode'])){
			$config = Db::name('config')->where(['key'=>'agentId'])->find()['value'];
			$recode = $config;//系统分配代理商
			$referee = Db::name('agents')
			->where(['id'=>$recode])
			->field('vid')
			->find();
			$aid = $recode;
			$vid = $referee['vid'];
			// $recode = $recode;
		}else{
			$referee = Db::name('agents')
			->where(['id'=>$_POST['refereecode']])
			->field('vid')
			->find();
			// dump($referee['vid']);die;
			if($referee!=null){
				$aid = $_POST['refereecode'];
				$vid = $referee['vid'];
			}else{
				return "<script>alert('推荐人不存在');history.go(-1);</script>";
			}
		}
		$usercode = $this->codeVerification($mobile,$code);
		// dump($usercode);die;
		if($usercode['msg'] != 'success') return "<script>alert('请输入正确的验证码');history.go(-1);</script>"; 
		if($pwd!=$pwds) return "<script>alert('请输入正确的验证码');history.go(-1);</script>"; 
		$name = Db::name('users')->where('phonenumber',createCode($mobile))->field('phonenumber')->find();
		if($name){
			return "<script>alert('用户已经存在');history.go(-1);</script>"; 
		}else{
		// if($_POST['yaoqingma']!=null){
//			$pwd  = $param['pwd'];
//			$pwds = $param['pwds'];
			// $code = $_POST['code'];
			if($pwd==$pwds){
				$usercode =  $this->GetRandStr();//随机数
				$data = [
					'phonenumber' => createCode($mobile),
					'password'	  => $pwd,
					'usercode'    => $usercode,
					'creationtime'=> date('Y-m-d H:i:s'),
					// 'refereecode' => $recode,//推荐人
					'aid'	  	  => $aid, //所属代理商id
					'vid'         => $vid
 				];
 				$user = Db::name('users')->insertGetId($data);
 				if(!$user){
 					$this->error('密码错误',('Userregister/index'));
 				}else{
					// Session::set('loginname',$user['name']);
					Session::set('uid',$user);
					Session::set('phonenumber',$mobile);
					Session::set('codes',mt_rand(1000,9999));
					//获取最后一次登录的ip
					$ip = Db::name('login_record')->where(['uid'=>$user])->find();
					if($ip){
						Session::set('lastIP',$ip['logintoip']);
						session::set('lasttime',$ip['logintime']);					
					}

					$d = [
						'uid' =>$user,
						'logintoip'=>$_SERVER['REMOTE_ADDR'],
						'logintime'=>date('Y-m-d H:i:s'),
                        'operation'=>'register:'.createCode($mobile),
					];
					$users = Db::name('login_record')->insert($d);
					Db::name('user_code')->where(['mobile'=>createCode($mobile)])->order('id','desc')->update(['state'=>1]);
					if($users){
						$this->success('注册登录成功','/home/certification/index');
					}
				}
			}else{
				$this->error('密码错误',('Userregister/index'));
			}
		}			
	}

	//验证用户是否注册
	public function userMobile(){
		$mobile = $_POST['mobile'];
		if(preg_match('/(^1[3|4|5|6|7|8|9]\d{9}$)|(^09\d{8}$)/', $mobile)!= 1) return ['msg'=>'格式错误'];
		if($mobile){
			$data = Db::name('users')->where('phonenumber',createCode($mobile))->find();
			if($data){
				return ['msg'=>'账号已经被注册'];
			}else{
				return ['msg'=>'success'];
			}
		}
	}

	public function userIdcard(){
        $mobile = $_POST['mobile'];
        if(preg_match('/^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/', $mobile)!= 1) return ['msg'=>'身份证格式错误'];
        if($mobile){
            $data = Db::name('users')->where('idcard',$mobile)->find();
            if($data){
                return ['msg'=>'账号已经被注册'];
            }else{
                return ['msg'=>'success'];
            }
        }
    }

	//验证验证码
	public function codeVerification($mobile,$code){
		$mobile = $_POST['mobile'];
		$code = $_POST['code'];
		if($mobile == null ){
			return ['msg'=>'手机号不能为空'];
		}
		if($code==null){
			return ['msg'=>'请输入验证码'];
		}else{
			$codes = Db::name('user_code')->where('mobile',createCode($mobile))->order('id desc')->find();
			if($codes['code']==$code){
				if(time()>=$codes['reg_time']+1800){
					return ['msg'=>'验证码超时'];
				}else{
					if($codes['state']==1){
						return ['msg'=>'验证码已经被使用'];
					}else{
						return ['msg'=>'success'];	
					}
				}
			}else{
				return ['msg'=>'验证码错误'];
			}			
		}
	}

	//推荐人查询验证
	public function refereeVerification($refereecode){
		$refereecode = $_POST['refereecode'];
		$referee = Db::name('users')->where('id',$refereecode)->find();
		if(!$referee){
			return json_encode(['msg'=>'推荐人不存在'],JSON_UNESCAPED_UNICODE);
		}else{
			return json_encode(['msg'=>'success']);
		}
	}



	public function GetRandStr(){   
	    $chars = array(   
	        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",    
	        "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",    
	        "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",    
	        "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",    
	        "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",    
	        "3", "4", "5", "6", "7", "8", "9"   
	    );   
	    $charsLen = count($chars) - 1;   
	    shuffle($chars);     
	    $output = "";   
	    for ($i=0; $i<4; $i++){   
	        $output .= $chars[mt_rand(0, $charsLen)];   
	    }    
	    return $output;    
	}


	//注册获取短信验证码
	public function registersendMsg(){
		// return 123;
		$mobile = $_POST['mobile'];
		//注册手机号是否已经注册
		$user = Db::name('users')->where(['phonenumber' => createCode($mobile)])->find();
		if($user){
			return ['msg'=>'手机号已经被注册'];
		}
		//一分钟只能发生一次
		$usercode = Db::name('user_code')->where('mobile',createCode($mobile))->order('id desc')->find();
		// dump($usercode);die;
		if($usercode['reg_time']+60 >= time()){
			return ['msg'=>'一分钟只能发送一次'];
		}
		$tplCode = 'SMS_134815253';
		$tplParam = rand(1000,9999);
		//短信发送
		$message = sendMsg($mobile,$tplCode,$tplParam);
		//$message = ['Message'=>'OK','Code'=>'OK'];

		if($message['Message']=='OK'){
			$data = [
				'mobile' => createCode($mobile),
				'code'   => $tplParam,
				'reg_time'=> time(),
			];
			$code = Db::name('user_code')->insert($data);
			if($code){
				return ['msg'=>'success'];
			}else{
				return ['msg'=>'验证码发送错误'];
			}
		}else{
			return ['msg'=>'验证码发送错误'];
		}

	}

    public function refereeCode(Request $request){
        $param = $request->post();
        $code = Db::name('agents')->where(['id'=>$param['recode']])->find();
        if($code){
            return ['msg'=>'success'];
        }else{
            return ['msg'=>'推荐码错误'];
        }
    }


    //注册添加s
    public function useraddCard(Request $request){
//        dump($_POST);die;
        $param = myarr($request->post());
        $idcard = $param['mobile'];
        $pwd = $param['pwd'];
        $pwds = $param['pwds'];
//        if(preg_match('/^[A-Za-z0-9]$/', $idcard)!= 1){
//            $this->error('身份证格式错误','Userregister/index',1);
//        }
        if(preg_match('/^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/', $idcard)!= 1){
            $this->error('身份证格式错误','Userregister/index',1);
        }
        if(preg_match('/^[A-Za-z0-9]{6,16}|\d{6,16}|[A-Za-z]{6,16}$/',$pwd) != 1){
            $this->error('密码格式错误','Userregister/index',1);
        }
        if(preg_match('/^[A-Za-z0-9]{6,16}|\d{6,16}|[A-Za-z]{6,16}$/',$pwds)!= 1){
            $this->error('密码格式错误','Userregister/index',1);
        }
        if(empty($_POST['refereecode'])){
            $config = Db::name('config')->where(['key'=>'agentId'])->find()['value'];
            $recode = $config;//系统分配代理商
            $referee = Db::name('agents')
                ->where(['id'=>$recode])
                ->field('vid')
                ->find();
            $aid = $recode;
            $vid = $referee['vid'];
            // $recode = $recode;
        }else{
            $referee = Db::name('agents')
                ->where(['id'=>$_POST['refereecode']])
                ->field('vid')
                ->find();
            // dump($referee['vid']);die;
            if($referee!=null){
                $aid = $_POST['refereecode'];
                $vid = $referee['vid'];
            }else{
                return "<script>alert('推荐人不存在');history.go(-1);</script>";
            }
        }
        $name = Db::name('users')->where('idcard',$idcard)->field('idcard')->find();
        if($name){
            return "<script>alert('用户已经存在');history.go(-1);</script>";
        }else{
            if($pwd==$pwds){
                $usercode =  $this->GetRandStr();//随机数
                $data = [
                    'idcard' => $idcard,
                    'password'	  => $pwd,
                    'usercode'    => $usercode,
                    'creationtime'=> date('Y-m-d H:i:s'),
                    // 'refereecode' => $recode,//推荐人
                    'aid'	  	  => $aid, //所属代理商id
                    'vid'         => $vid
                ];
                $user = Db::name('users')->insertGetId($data);
                if(!$user){
                    $this->error('密码错误',('Userregister/index'));
                }else{
                    // Session::set('loginname',$user['name']);
                    Session::set('uid',$user);
                    Session::set('phonenumber','');
                    Session::set('codes',mt_rand(1000,9999));
                    //获取最后一次登录的ip
                    $ip = Db::name('login_record')->where(['uid'=>$user])->find();
                    if($ip){
                        Session::set('lastIP',$ip['logintoip']);
                        session::set('lasttime',$ip['logintime']);
                    }
                    $d = [
                        'uid' =>$user,
                        'logintoip'=>$_SERVER['REMOTE_ADDR'],
                        'logintime'=>date('Y-m-d H:i:s'),
                        'operation'=>'register:'.$idcard,
                    ];
                    $users = Db::name('login_record')->insert($d);
                    if($users){
                        $this->success('注册登录成功','/home/certification/index');
                    }
                }
            }else{
                $this->error('密码错误',('Userregister/index'));
            }
        }
    }
}
